<?php

namespace App\Http\Controllers\Api\Third;

use App\GameZghpt;
use App\Http\Controllers\Controller;
use App\Jobs\SaveUserAvatar;
use App\Jobs\SendUserQrcode;
use App\Jobs\JoinTeam;
use App\Models\Coupon\UserCoupon;
use App\Order;
use App\Product;
use App\Qrcode;
use App\User;
use App\UserChange;
use App\UserCoinLog;
use App\WechatMenu;
use Carbon\Carbon;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order as WMOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

class WechatController extends Controller
{
    protected $wechat;
    protected $wechat_receipt;
    protected $wechat_payment;
    protected $wechat_app;

    public function __construct()
    {
        $this->wechat = app('wechat');
        $this->wechat_receipt = new Application([
            'app_id' => env('RECEIPT_WECHAT_APPID'),
            'secret' => env('RECEIPT_WECHAT_SECRET'),
            'token' => env('RECEIPT_WECHAT_TOKEN'),
            'aes_key' => env('RECEIPT_WECHAT_AES_KEY'),
            'payment' => [
                'merchant_id' => env('RECEIPT_WECHAT_PAYMENT_MERCHANT_ID'),
                'key' => env('RECEIPT_WECHAT_PAYMENT_KEY'),
                'cert_path' => env('RECEIPT_WECHAT_PAYMENT_CERT_PATH'),
                'key_path' => env('RECEIPT_WECHAT_PAYMENT_KEY_PATH'),
                'notify_url' => env('RECEIPT_WECHAT_PAYMENT_NOTIFY_URL'),
            ],
        ]);
        $this->wechat_payment = new Application([
            'app_id' => env('PAYMENT_WECHAT_APPID'),
            'secret' => env('PAYMENT_WECHAT_SECRET'),
            'token' => env('PAYMENT_WECHAT_TOKEN'),
            'aes_key' => env('PAYMENT_WECHAT_AES_KEY'),
            'payment' => [
                'merchant_id' => env('PAYMENT_WECHAT_PAYMENT_MERCHANT_ID'),
                'key' => env('PAYMENT_WECHAT_PAYMENT_KEY'),
                'cert_path' => env('PAYMENT_WECHAT_PAYMENT_CERT_PATH'),
                'key_path' => env('PAYMENT_WECHAT_PAYMENT_KEY_PATH'),
                'notify_url' => env('PAYMENT_WECHAT_PAYMENT_NOTIFY_URL'),
            ],
        ]);
        $this->wechat_app = new Application([
            'app_id' => env('APP_WECHAT_APPID'),
            'secret' => env('APP_WECHAT_SECRET'),
            'token' => env('APP_WECHAT_TOKEN'),
            'aes_key' => env('APP_WECHAT_AES_KEY'),
            'payment' => [
                'merchant_id' => env('APP_WECHAT_PAYMENT_MERCHANT_ID'),
                'key' => env('APP_WECHAT_PAYMENT_KEY'),
                'cert_path' => env('APP_WECHAT_PAYMENT_CERT_PATH'),
                'key_path' => env('APP_WECHAT_PAYMENT_KEY_PATH'),
                'notify_url' => env('APP_WECHAT_PAYMENT_NOTIFY_URL'),
            ],
        ]);
    }

    public function index()
    {
        $server = $this->wechat->server;
        $server->setMessageHandler(function ($message) {
            $openid = $message->FromUserName;
            switch ($message->MsgType) {
                case 'event':
                    switch ($message->Event) {
                        case 'subscribe':
                            $wechat_user = $this->wechat->user->get($openid);
                            $unionid = $wechat_user['unionid'];

                            if ($user = User::where('openid', $openid)->first()) {
                            } elseif ($user = User::where('unionid', $unionid)->first()) {
                                $user->openid = $openid;
                                $user->save();
                            } else {
                                $user = new User;
                                $user->openid = $openid;
                                $user->avatar = $wechat_user['headimgurl'];
                                $user->nickname = $wechat_user['nickname'];
                                $user->sex = $wechat_user['sex'];
                                $user->country = $wechat_user['country'];
                                $user->province = $wechat_user['province'];
                                $user->city = $wechat_user['city'];
                                $user->password = '';
                                $user->save();

                                dispatch(new SaveUserAvatar($user));
                            }

                            if (!$user->unionid) {
                                $user->unionid = $wechat_user['unionid'];
                                $user->save();
                            }

                            //关联处理
                            if ($message->EventKey && substr($message->EventKey, 0, 8) == 'qrscene_' && !$user->finder_id) {
                                $scene_id = intval(substr($message->EventKey, 8));
                                if ($user->id != $scene_id) {
                                    $user->finder_id = $scene_id;
                                    $user->save();

                                    $finder = User::where('id', $scene_id)->first();
                                    $this->wechat->staff->message('恭喜！' . $user->nickname . '成为你的粉丝。')->to($finder->openid)->send();
                                }
                            }

                            $this->wechat->staff->message('您好，欢迎关注欢乐菠萝！')->to($openid)->send();
                            break;
                        case 'unsubscribe':
                            break;
                        case 'CLICK':
                            switch ($message->EventKey) {
                                case 'QRCODE':
                                    $user = User::where('openid', $openid)->first();

                                    $qrcode = Qrcode::find(3);
                                    dispatch(new SendUserQrcode($user, $qrcode));

                                    $this->wechat->staff->message('二维码正在生成中，稍后通过消息发给您')->to($openid)->send();
                                    break;
                                case 'CHAT':
                                    $this->wechat->staff->message('快乐大菠萝微信群，每天红包活动，福利多多，惊喜多多，加欢乐客服微信号：yskj8868，邀约进群，抢大红包。')->to($openid)->send();
                                    break;
                                case 'SIGN':
                                    return <<<EOF
每日一签，已迁移到〈聚宝盆游戏〉的每日一赚，请下载app赚取更多小妖币！
好玩是第一生产力！
EOF;
                                    break;
                            }
                            break;
                    }
                    break;
                case 'text':
                    return "您的消息我们已经收到了哦！";
                    break;
                default:
                    return "您好，欢迎关注欢乐菠萝！";
            }
        });
        $response = $server->serve();
        $response->send();
    }

    public function receipt()
    {
        $server = $this->wechat_receipt->server;
        $response = $server->serve();
        $response->send();
    }

    public function payment()
    {
        $server = $this->wechat_payment->server;
        $response = $server->serve();
        $response->send();
    }


    /**
     * 商品支付
     * @param $user
     * @param $mallOrder
     * @param $goods
     * @param string $type
     * @return mixed
     */
    public function goodsPay($user,$mallOrder,$goods, $type)
    {
        if ($type == 'JSAPI') {
            if (env('WECHAT_APPID') != env('RECEIPT_WECHAT_APPID')) {
                if (!$user->openid_receipt) {
                    return response()->json(['code' => 9001, 'msg' => '未绑定收款帐号！', 'results' => ['user' => Crypt::encrypt($user->id)]]);
                }
                $wechat = $this->wechat_receipt;
                $openid = $user->openid_receipt;
            } else {
                $wechat = $this->wechat;
                $openid = $user->openid;
            }
        }
        if ($type == 'APP') {
            $wechat = $this->wechat_app;
            $openid = $user->openid_app;
        }

        $order = new Order;
        $order->trade_id = '';
        $order->user_id = $user->id;
        $order->related_id = $mallOrder->id;
        $order->total = ($goods->need_xyb/100);
        $order->type = 2;//1.product 2.mall
        $order->save();

        $order->trade_id = Carbon::now()->format('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . $order->id;
        $order->save();

        $attributes = [
            'trade_type' => $type,
            'body' => $goods->name,
            'detail' => $goods->name,
            'out_trade_no' => $order->trade_id,
            'total_fee' => ($order->total * 100),
            'openid' => $openid,
        ];
        $order = new WMOrder($attributes);
        $data = $wechat->payment->prepare($order);

        if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
            $prepay_id = $data->prepay_id;
            switch ($type) {
                case  'JSAPI':
                    $data = $wechat->payment->configForPayment($prepay_id);
                    break;
                case  'APP':
                    $data = $wechat->payment->configForAppPayment($prepay_id);
                    break;
            }
            return json_encode(['code' => 1000, 'results' => $data]);
        }
        return json_encode(['code' => 9000, 'msg' => '创建订单失败！']);
    }


    public function prepare(Request $request)
    {
        $user = auth()->user();
        $type = $request->input('type', 'JSAPI');

        if ($type == 'JSAPI') {
            if (env('WECHAT_APPID') != env('RECEIPT_WECHAT_APPID')) {
                if (!$user->openid_receipt) {
                    return response()->json(['code' => 9001, 'msg' => '未绑定收款帐号！', 'results' => ['user' => Crypt::encrypt($user->id)]]);
                }
                $wechat = $this->wechat_receipt;
                $openid = $user->openid_receipt;
            } else {
                $wechat = $this->wechat;
                $openid = $user->openid;
            }
        }
        if ($type == 'APP') {
            $wechat = $this->wechat_app;
            $openid = $user->openid_app;
        }

        if ($request->has('charge')) {
            $charge = intval(abs($request->input('charge')));
            if ($charge) {
                if (!$product = Product::where('value', $charge)->where('type', 1)->first()) {
                    $product = new Product;
                    $product->business_id = 0;
                    $product->name = '支付' . $charge;
                    $product->price = $charge;
                    $product->type = 1;
                    $product->value = $charge;
                    $product->save();
                }
            }
        } else {
            $product_id = $request->input('product');
            if ($product_id == 1) {

                if ($user->orders()->where('related_id', $product_id)->where('type', 1)->where('status', 1)->exists()) {
                    return response()->json(['code' => 9002, 'msg' => '您已购买了VIP哦，赶紧去玩游戏吧(♥◠‿◠)ﾉ']);
                }

                if (!in_array($user->id, [28757])) {
                    // 19点开抢VIP
                    if (time() < mktime(19, 0, 0)) {
                        return response()->json(['code' => 9002, 'msg' => 'VIP将在' . Carbon::today()->format('Y-m-d') . ' 19点开放抢购！']);
                    }

                    // 19点15分停止抢VIP
                    if (time() > mktime(19, 15, 0)) {
                        return response()->json(['code' => 9002, 'msg' => 'VIP已被抢空了，明天赶早哦！']);
                    }
                }
            }
            if ($product_id == 34 && $user->orders()->where('related_id', $product_id)->where('type', 1)->where('status', 1)->exists()) {
                return response()->json(['code' => 9003, 'msg' => '您已购买了金蛋哦，赶紧去玩游戏吧(♥◠‿◠)ﾉ']);
            }
            $product = Product::findOrFail($product_id);
        }

        $order = new Order;
        $order->trade_id = '';
        $order->user_id = $user->id;
        $order->related_id = $product->id;
        $order->total = $product->price;
        $order->type = 1;//1.product 2.mall
        $order->save();

        $order->trade_id = Carbon::now()->format('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT) . $order->id;
        $order->save();

        $attributes = [
            'trade_type' => $type,
            'body' => $product->name,
            'detail' => $product->name,
            'out_trade_no' => $order->trade_id,
            'total_fee' => ($order->total * 100),
            'openid' => $openid,
        ];
        $order = new WMOrder($attributes);
        $data = $wechat->payment->prepare($order);

        if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
            $prepay_id = $data->prepay_id;
            switch ($type) {
                case  'JSAPI':
                    $data = $wechat->payment->configForPayment($prepay_id);
                    break;
                case  'APP':
                    $data = $wechat->payment->configForAppPayment($prepay_id);
                    break;
            }

            return response()->json(['code' => 1000, 'results' => $data]);
        }

        return response()->json(['code' => 9000, 'msg' => '创建订单失败！']);
    }

    public function notify($type = 'JSAPI')
    {
        if ($type == 'JSAPI') {
            if (env('WECHAT_APPID') != env('RECEIPT_WECHAT_APPID')) {
                $wechat = $this->wechat_receipt;
            } else {
                $wechat = $this->wechat;
            }
        }
        if ($type == 'APP') {
            $wechat = $this->wechat_app;
        }

        $response = $wechat->payment->handleNotify(function ($notify, $successful) {

            try {
                DB::beginTransaction();
                Log::debug($notify->out_trade_no);
                $order = Order::where('trade_id', $notify->out_trade_no)->where('status', 0)->sharedLock()->first();
                if (!$order) {
                    return true;
                }

                if ($successful) {
                    $order->status = 1;
                    $order->save();

                    $user = $order->user;
                    Log::debug($order);
                    switch ($order->type) {
                        case 1:
                            //product
                            $product = $order->product;
                            $business = $product->business;
                            switch ($product->type) {
                                case 1:
                                    $key = '0-' . $user->id . '-' . $product->value . '-' . $notify->transaction_id . '-1';
                                    //金币日志
                                    UserCoinLog::log(0, $user->id, UserCoinLog::TYPE_XYB, $product->value, '充值', $key);

                                    // 每充值一百送2金元宝
                                    $product_value = intval($product->value);
                                    $yb_num = intval($product_value/100) * 2;
                                    // 新增用户金元宝
                                    $datas = [];
                                    for($i=0; $i<$yb_num; $i++) {
                                        $datas[] = [ 'ybid' => Uuid::uuid1(), 'uid' => $user->id, 'origin_type' => 'cz' ];
                                    }
                                    if (!empty($datas)) {
                                        DB::table('game_jbp_user_yb')->insert($datas);
                                    }

                                    break;
                                case 2:
                                    switch ($business->index) {
                                        case 'zghpt':
                                            $user->{'game_' . $business->index}->update(['level' => $product->value]);

                                            $quota = rand(2000, 3000) / 100;

                                            if ($user->finder_id > 0) {
                                                $finder = User::find($user->finder_id);

                                                $key = $business->id . '-' . $finder->id . '-60-' . $order->id . '-3';
                                                UserCoinLog::log($business->id, $finder->id, UserCoinLog::TYPE_XYB, 60, $business->name . '购买VIP上线奖励', $key);
                                                try {
                                                    $this->wechat->staff->message('你的粉丝升级了VIP，你获得6000个小妖币推荐奖励.')->to($finder->openid)->send();
                                                } catch (\Exception $e) {
                                                }

                                                if ($gameZghpt = $finder->game_zghpt) {
                                                    $gameZghpt->quota += $quota;
                                                    $gameZghpt->save();
                                                } else {
                                                    $gameZghpt = new GameZghpt();
                                                    $gameZghpt->user_id = $finder->id;
                                                    $gameZghpt->quota = $quota;
                                                    $gameZghpt->level = 0;
                                                    $gameZghpt->save();
                                                }
                                            }

                                            $key = $business->id . '-' . $user->id . '-10-' . $order->id . '-8';
                                            UserCoinLog::log($business->id, $user->id, UserCoinLog::TYPE_XYB, 10, $business->name . '购买VIP奖励', $key);
                                            try {
                                                $this->wechat->staff->message('你升级了VIP，获得1000个小妖币奖励.')->to($user->openid)->send();
                                            } catch (\Exception $e) {
                                            }

                                            $gameZghpt = $user->game_zghpt;

                                            $gameZghpt->quota += $quota;
                                            $gameZghpt->save();

                                            $coupon = DB::table('coupon')->where('id', 3)->orderBy('id', 'desc')->first();

                                            //生成优惠卷信息
                                            $userCouponModel = new UserCoupon;
                                            $userCouponModel->coupon_id = $coupon->id;
                                            $userCouponModel->name = $coupon->name;
                                            $userCouponModel->user_id = $user->id;
                                            $userCouponModel->code = Uuid::uuid1();
                                            $userCouponModel->min_price = $coupon->min_price;
                                            $userCouponModel->max_value = $coupon->max_value;
                                            $userCouponModel->status = 1;
                                            $userCouponModel->remark = '';
                                            $userCouponModel->goods_id = $coupon->goods_id;
                                            $userCouponModel->scope_type = $coupon->scope_type;
                                            $userCouponModel->ukey = $user->id . '-' . Carbon::now()->format('YmdHi');
                                            $userCouponModel->save();

//                                            // 蚂蚁特工队
//                                            $uid = $user->id;
//                                            DB::table('game_ant_user')->insert([
//                                                'uid' => $user->id,
//                                                'finder_uid' => $user->finder_id,
//                                                'nickname' => $user->nickname,
//                                                'avatar' => $user->avatar,
//                                                'province' => $user->province,
//                                                'city' => $user->city,
//                                            ]);
//                                            dispatch(new JoinTeam($uid));

                                            break;
                                        case 'egg':
                                            // 一百万的蛋

                                            // 升级银蛋到金蛋
                                            $xyb_upper_limit = rand(10, 20);
                                            DB::table('game_egg_user')->where('mid', $user->id)->update([
                                                'level' => 2,       /* 升级到银蛋 */
                                                'lottery_num' => 1, /* 给予一次抽奖机会 */
                                                'xyb_upper_limit' => $xyb_upper_limit /* 用户可领取小妖币上限 */
                                            ]);

                                            // 判断订单总额是否大于零
                                            $total = $order->total;
                                            if ($total > 0) {
                                                // 二级分销
                                                if ($user->finder_id > 0) {
                                                    // 上级
                                                    $finder = User::find($user->finder_id);

                                                    // 判断上级是否满足升级钻石蛋条件，即有两个粉丝升级了金蛋
                                                    $fans_cnt = DB::table('game_egg_user')
                                                        ->join('user', 'user.id', '=', 'game_egg_user.mid')
                                                        ->select('user.id')
                                                        ->where('game_egg_user.level', 2)
                                                        ->where('user.finder_id', $finder->id)
                                                        ->count();
                                                    if ($fans_cnt >= 2) {
                                                        // 只允许金蛋用户升级到钻石蛋
                                                        $cnt = DB::table('game_egg_user')->where('mid', $finder->id)->where('level', 2)->count();
                                                        if ($cnt == 1) {
                                                            // 更新上级用户为钻石蛋，设置小妖币上限阀值
                                                            $xyb_upper_limit = rand(200, 300);
                                                            DB::table('game_egg_user')->where('mid', $finder->id)->where('level', 2)->update(['level' => 3, 'xyb_upper_limit' => $xyb_upper_limit]);
                                                            // 提示用户
                                                            try {
                                                                $this->wechat->staff->message('您的两位粉丝升级了鸡蛋，您获得稀有钻石蛋的奖励.')->to($finder->openid)->send();
                                                            } catch (\Exception $e) {
                                                            }
                                                        }
                                                    }

                                                    // 分3块钱
                                                    $key = $business->id . '-' . $finder->id . '-3-' . $order->id . '-3';
                                                    UserCoinLog::log($business->id, $finder->id, UserCoinLog::TYPE_XYB, 3, $business->name . '购买金蛋上线奖励', $key);
                                                    // 提示用户
                                                    try {
                                                        $this->wechat->staff->message('您的粉丝升级了鸡蛋，您获得300个小妖币推荐奖励.')->to($finder->openid)->send();
                                                    } catch (\Exception $e) {

                                                    }

                                                    if ($finder->finder_id > 0) {
                                                        // 上上级
                                                        $finder2 = User::find($finder->finder_id);
                                                        // 分3块钱
                                                        $key = $business->id . '-' . $finder2->id . '-3-' . $order->id . '-3';
                                                        UserCoinLog::log($business->id, $finder2->id, UserCoinLog::TYPE_XYB, 3, $business->name . '购买金蛋上线奖励', $key);
                                                        // 提示用户
                                                        try {
                                                            $this->wechat->staff->message('您的粉丝升级了金蛋，您获得300个小妖币推荐奖励.')->to($finder2->openid)->send();
                                                        } catch (\Exception $e) {

                                                        }
                                                    }
                                                }
                                            }
                                            break;
                                    }
                                    break;
                            }
                            break;
                        case 2:
                            //mall
                            Log::debug($order->related_id);
                            $mallOrder = \App\Models\Mall\Order::find($order->related_id);
                            $mallOrder->status = 1;
                            $mallOrder->save();
                            break;
                    }

                }
                DB::commit();

            } catch (\Exception $e) {
                DB::rollBack();
                return false;
            }

            return true;
        });

        return $response;
    }

    public function lucky_money(Request $request, $type = 'JSAPI')
    {
        $user = auth()->user();

//        if ( !in_array($user->id, [5,6]) ) {
//            return response()->json(['code' => 9002, 'msg' => '系统繁忙，请稍候再试']);
//        }

        if (env('WECHAT_APPID') != env('PAYMENT_WECHAT_APPID')) {
            if (!$user->openid_payment) {
                return response()->json(['code' => 9001, 'msg' => '未绑定收款帐号！', 'results' => ['user' => Crypt::encrypt($user->id)]]);
            }
            $wechat = $this->wechat_payment;
            $openid = $user->openid_payment;
        } else {
            $wechat = $this->wechat;
            $openid = $user->openid;
        }
        if ($type == 'APP') {
            $wechat = $this->wechat_app;
            $openid = $user->openid_app;
        }

        if ($user->XYB < 10) {
            return response()->json(['code' => 9002, 'msg' => '红包不足10，无法发放！']);
        }

        $amount = $request->input('amount', 0);
        if(!in_array($amount, array(10, 50, 100, 200))) {
            return response()->json(['code' => 9004, 'msg' => '红包金额有误，请重新选择']);
        }

        $key = Carbon::now()->format('YmdHi');

        $change = $user->changes()->orderBy('created_at', 'desc')->first();
        if ($change && $change->created_at->format('YmdHi') == $key) {
            return response()->json(['code' => 9003, 'msg' => '一分钟只能发放红包一次，请稍候再试！']);
        }

        if ($user->changes()->where('created_at', '>=', Carbon::today()->startOfDay())->count() >= 10) {
            return response()->json(['code' => 9004, 'msg' => '由于微信限制，每天只能发放红包10次，请明天再试吧！']);
        }

        try {
            if ($user->XYB < $amount) {
                return response()->json(['code' => 9004, 'msg' => '红包不足，无法发放！']);
            }

            $userChange = new UserChange;
            $userChange->trade_id = Carbon::now()->format('YmdHis') . str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
            $userChange->user_id = $user->id;
            $userChange->key = $user->id . '-' . Carbon::now()->format('YmdHi');
            $userChange->amount = $amount;
            $userChange->save();

//            DB::beginTransaction();

            $key = '0-' . $user->id . '-' . -$amount . '-' . time() . '-4';
            UserCoinLog::log(0, $user->id, UserCoinLog::TYPE_XYB, -$amount, '提现', $key);

            $luckyMoney = $wechat->lucky_money;
            $luckyMoneyData = [
                'mch_billno' => $userChange->trade_id,
                'send_name' => '欢乐菠萝',
                're_openid' => $openid,
                'total_num' => 1,
                'total_amount' => bcmul($amount, 0.95, 2) * 100,
                'wishing' => '兑换红包',
                'act_name' => '欢乐菠萝',
                'remark' => '欢乐菠萝',
            ];
            $data = $luckyMoney->sendNormal($luckyMoneyData);

            if ($data->return_code == 'SUCCESS' && $data->result_code == 'SUCCESS') {
                $userChange->status = 1;
                $userChange->save();
//                DB::commit();
                return response()->json(['code' => 1000, 'results' => ['XYB' => $user->XYB]]);
            } else {
//                DB::rollback();

                //发出警报
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send_batch.json");
                curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_HEADER, FALSE);
                curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile_list' => '13726873311,13602411466,13430252975', 'message' => '你好，发现异常情况。项目：欢乐菠萝，UID：' . $user->id . '，描述：' . $data->err_code_des . '。【小妖传媒】'));
                $res = curl_exec($ch);
            }
        } catch (\Exception $e) {
//            DB::rollback();
        }

        return response()->json(['code' => 9000, 'msg' => '兑换红包失败，小妖币将在5分钟内退回您的账户！']);
    }

    public function menu()
    {
        $menu = $this->wechat->menu;

        $menu->destroy();

        $parameters = array(
            'view' => 'url',
            'click' => 'key'
        );
        $buttons = array();

        $wechatMenuGroup = WechatMenu::where('parent_id', 0)->orderBy('sort', 'asc')->get();
        foreach ($wechatMenuGroup as $group) {
            if ($group->children()->count()) {
                $subs = array();
                foreach ($group->children()->orderBy('sort', 'asc')->get() as $wechatMenu) {
                    $subs[] = array(
                        'type' => $wechatMenu->type,
                        'name' => $wechatMenu->name,
                        $parameters[$wechatMenu->type] => $wechatMenu->parameter
                    );
                }

                $buttons[] = array(
                    'name' => $group->name,
                    'sub_button' => $subs
                );
            } else {
                $buttons[] = array(
                    'type' => $group->type,
                    'name' => $group->name,
                    $parameters[$group->type] => $group->parameter
                );
            }
        }

        $response = $menu->add($buttons);

        return $response;
    }

    /**
     * 微信分享
     *
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function share(Request $request)
    {
        $no = str_random(16);

        $da['appId'] = env('WECHAT_APPID');

        $da['timestamp'] = time();
        $da['nonceStr'] = $no;

        $da['error'] = '';
        $da['type'] = TRUE;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . env('WECHAT_APPID') . '&secret=' . env('WECHAT_SECRET');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            $da['error'] = 'Errno' . curl_error($ch);
            $da['type'] = FALSE;
        }
        curl_close($ch);
        $postObj = json_decode($tmpInfo);
        $access_token = $postObj->access_token;

        //获取jsapi_ticket
        $ls = file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $postObj->access_token . '&type=jsapi');
        $js = json_decode($ls, true);
        $da['jsapi_ticket'] = $js['ticket'];
        $str1 = 'jsapi_ticket=' . $da['jsapi_ticket'] . '&noncestr=' . $no . '&timestamp=' . $da['timestamp'] . '&url=' . $request->input('site_url');

        $da['signature'] = sha1($str1);

        return response()->json($da);
    }

    private function sign($openid)
    {
        $user = User::where('openid', $openid)->first();

        $mottos = ['好玩才是第一生产力'];

        $XYB = 0.5;
        $G1 = DB::select("SELECT nickname,s FROM (SELECT mid,SUM(sh_jb) s FROM `pan_fishing` WHERE created_at>'" . Carbon::now()->subDay()->format('Y-m-d H:i:s') . "' AND sh_jb>0 GROUP BY mid) t LEFT JOIN `user` u ON t.mid=u.id ORDER BY s DESC limit 1");
        $G2 = DB::select("SELECT nickname,s FROM (SELECT user_id,SUM(gold) s FROM `game_sgdzz_order_detail_log` WHERE created_at>'" . Carbon::now()->subDay()->format('Y-m-d H:i:s') . "' AND unpay=0 AND is_win=1 GROUP BY user_id) t LEFT JOIN `user` u ON t.user_id=u.id ORDER BY s DESC limit 1");
        $G3 = DB::select("SELECT nickname,s FROM (SELECT user_id,SUM(get_xyb) s FROM `game_hlgc_record_log` WHERE created_time>'" . Carbon::now()->subDay()->format('Y-m-d H:i:s') . "' AND bet_result=1 GROUP BY user_id) t LEFT JOIN `user` u ON t.user_id=u.id ORDER BY s DESC limit 1");
        $G4 = DB::select("SELECT nickname,s FROM (SELECT user_id,SUM(bet_xyb) s FROM `game_cq_record_log` WHERE created_time>'" . Carbon::now()->subDay()->format('Y-m-d H:i:s') . "' AND bet_result=1 GROUP BY user_id) t LEFT JOIN `user` u ON t.user_id=u.id ORDER BY s DESC limit 1");
        $MOTTO = $mottos[array_rand($mottos)];

        $signed = true;
        $key = '0-' . $user->id . '-' . $XYB . '-' . Carbon::now()->format('Ymd') . '-13';
        if (!UserCoinLog::where('user_id', $user->id)->where('key', $key)->exists()) {
            $signed = false;
            UserCoinLog::log(0, $user->id, UserCoinLog::TYPE_XYB, $XYB, '签到奖励', $key);
        }

        $template = <<<EOF
%s

24小时战报：
🐟欢乐钓鱼：%s，24小时内赢取了%s小妖币！
🍌水果大作战：%s，24小时内赢取了%s小妖币！
🏠欢乐攻城：%s，24小时内赢取了%s小妖币！
✊️趣味猜拳：%s，24小时内赢取了%s小妖币！

%s！
EOF;

        $this->wechat->staff->message(
            sprintf(
                $template,
                ($signed ? '🏆您已签到，成功获得50小妖币！' : sprintf('🏅签到成功，您获得%u个小妖币奖励！', ($XYB * 100))),
                ($G1 ? $G1[0]->nickname : '...'),
                ($G1 ? ($G1[0]->s * 100) : '0'),
                ($G2 ? $G2[0]->nickname : '...'),
                ($G2 ? ($G2[0]->s * 100) : '0'),
                ($G3 ? $G3[0]->nickname : '...'),
                ($G3 ? ($G3[0]->s * 100) : '0'),
                ($G4 ? $G4[0]->nickname : '...'),
                ($G4 ? ($G4[0]->s * 100) : '0'),
                $MOTTO)
        )->to($openid)->send();
    }
}
